package esa.isoc.statistics;

import java.io.File;
import java.io.FileFilter;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class FileManager {
	public final static File DIRECTORY = new File("/home/esalazar/web-workspace/integral-statistics/resources/");
	public List<StatisticFile> getStatisticsFiles() {
		 
		
		FileFilter filter = new StatisticsFileFilter(); 
		List<File> files = Arrays.asList(DIRECTORY.listFiles(filter));
		Collections.sort(files, new Comparator<File>() {
			@Override
			public int compare(File f1, File f2) {			 
				return f1.getName().compareTo(f2.getName());
			}
		});
		List<StatisticFile> statisticFiles = new ArrayList<StatisticFile>();
		for (File file : files) {
			StatisticFile stFile = new StatisticFile(file.getName()); 
			
			add(statisticFiles, stFile);
		}
		
		
		
		return statisticFiles;
	}
	private void add(final List<StatisticFile> statisticFiles,final StatisticFile stFile) {
		
		List<File> files = Arrays.asList(DIRECTORY.listFiles(new FileFilter() {
			
			@Override
			public boolean accept(File pathname) {
				
				return pathname.getName().equals(stFile.getRevolutionNumber())
			   || pathname.getName().startsWith(stFile.getRevolutionNumber() + "_");
			}
		} ));
		StatisticFile maxVersionFile = new StatisticFile(stFile.revolutionNumber, 0);
		
		
		for (File file : files) {
			StatisticFile currentFile = new StatisticFile(file.getName());
			if (currentFile.isNewerThan(maxVersionFile)) {
				maxVersionFile = currentFile;
			}
		}
		if (maxVersionFile.equals(stFile)) {
			statisticFiles.add(stFile);
		}
				
		
	}
	/*private File createTestFile(String fileName, int position,
			int version) {
		StringBuilder sb = new StringBuilder();
		try {
			if (position > -1) {
				sb.append(fileName);
			}
			sb.append("_");
			version++;
			if (version < 10) {
				sb.append("0");
			}
			sb.append(version);
			sb.append(version + ".STATS");
			return new File(DIRECTORY, sb.toString());
		} catch (Exception e) {
			return new File(DIRECTORY, "test");
		}
	}*/
}
